import React from 'react';
import ReactDOM from 'react-dom';
import './five.css';

function Square(props) {
    return (
        <button className="square" onClick={props.onClick}>
            {props.value}
        </button>
    );
}

class Board extends React.Component {
    state = {
        menuList: []
    };

    constructor(props) {
        super(props)
        this.state = {
            currentIndex: 0,
        }
    }

    renderSquare(i) {
        return <Square key={i} value={this.props.squares[i]}
                       onClick={() => {
                           let currentIndex = i + 1;
                           this.state = {
                               currentIndex: currentIndex,
                           }
                           this.props.onClick(i, this.state.currentIndex);
                       }}
        />;
    }

    render() {
        return (
            Array(this.props.total).fill(null).map((v, index) => {
                return (
                    <div className="board-row" key={index}>
                        {
                            Array(this.props.total).fill(null).map((v, index1) => {
                                return (
                                    this.renderSquare(this.props.total * index + index1)
                                )
                            })}
                    </div>)
            })
        );
    }
}

class Game extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            history: [{
                squares: Array(225).fill(null),
            }],
            stepNumber: 0,
            xIsNext: true,
            selected: 0,
            currentIndex: 0,
            total: 15,
            length: 5,
            winner: '',
            close: false,
            player: 'play'
        };
    }

    handleClick(i, currentIndex) {
        this.setState({
            currentIndex: currentIndex,
        });
        const history = this.state.history.slice(0, this.state.stepNumber + 1);
        const current = history[history.length - 1];
        const squares = current.squares.slice();
        let t = squares[i];
        if (this.state.close || t) {
            return;
        }
        squares[i] = this.state.xIsNext ? 'X' : 'O';
        let winner = calculateWinner(squares, this.state.xIsNext, currentIndex, this.state.length, this.state.total);
        if (winner && this.state.close) {
            return;
        }
        let historyTemp = history.concat([{squares: squares,}]);
        this.setState({
            history: historyTemp,
            stepNumber: history.length,
            xIsNext: !this.state.xIsNext,
            winner: winner,
            close: winner ? true : false,
            player: winner ? 'win' : 'play',
        });
    };

    jumpTo(step) {
        console.log(step)
        if (step){
            this.setState({
                stepNumber: step,
                xIsNext: (step % 2) === 0,
            });
        }else {
            this.setState({
                history: [{
                    squares: Array(225).fill(null),
                }],
                stepNumber: 0,
                xIsNext: true,
                selected: 0,
                currentIndex: 0,
                total: 15,
                length: 5,
                winner: '',
                close: false,
                player: 'play'
            });
        }

    };

    render() {
        const history = this.state.history;
        const current = history[this.state.stepNumber];
        const moves = history.map((step, move) => {
            const desc = move ?
                '第' + move + '步' :
                '重新开始';
            return (
                <li key={move}>
                    <button onClick={() => this.jumpTo(move)}>{desc}</button>
                </li>
            );
        });

        let status;
        if (this.state.winner) {
            status = this.state.winner + '赢了!!!';

        } else {
            status = '下棋方: ' + (this.state.xIsNext ? 'X' : 'O');
        }
        return (
            <div className="game">
                <div className='bk'>
                    {
                        Array(this.state.total-1).fill(null).map((v, index) => {
                            return (
                                <div className="x" key={index}>
                                    {
                                        Array(this.state.total-1).fill(null).map((v, index1) => {
                                            return (
                                                <button className='y' key={index1}></button>
                                            )
                                        })}
                                </div>)
                        })}
                </div>
                <div className="circle">
                </div>

                <div className="game-board">
                    <Board
                        selected={this.state.selected}
                        squares={current.squares}
                        currentIndex={this.state.currentIndex}
                        total={this.state.total}
                        onClick={(i, currentIndex) => this.handleClick(i, currentIndex)}
                    />
                </div>

                <div className="game-info">
                    <div className={this.state.player}>{status}</div>
                    <ol>{moves}</ol>
                </div>

            </div>
        );
    }
}

// ========================================

ReactDOM.render(
    <Game/>,
    document.getElementById('root')
);

function calculateWinner(squares, xIsThis, currentIndex, length, total) {
    const type = xIsThis ? 'X' : 'O';
    const result = [];
    for (let i = 0; i < squares.length; i++) {
        if (squares[i] === type) {
            result.push(i + 1);
        }
    }
    let flag = check(result, currentIndex, length, total);
    return flag ? type : '';

}


function alg(length, currentIndex, total, result, count,operation) {
    for (let i = 0; i < length; i++) {
        let value = -1;
        if (operation==='xAdd'){
            value = currentIndex + i;
        }else if (operation==='xSub'){
            value = currentIndex - i;
        }else if (operation==='yAdd'){
            value = currentIndex + i * total;
        }else if (operation==='ySub'){
            value = currentIndex - i * total;
        }else if (operation==='xAddYSub'){
            value = currentIndex + i * (total + 1);
        }else if (operation==='xSubYAdd'){
            value = currentIndex - i * (total + 1);
        }else if (operation==='xSubYSub'){
            value = currentIndex + i * (total - 1);
        }else if (operation==='xAddYAdd'){
            value = currentIndex - i * (total - 1);
        }
        let b = result.indexOf(value) !== -1;
        if (b) {
            count++;
        } else {
            break;
        }

    }
    return count;
}

function check(result, currentIndex, length, total) {
    let count = 0;
    count = alg(length, currentIndex, total, result, count,'xAdd');
    if (count === length || alg(length - count + 1, currentIndex, total, result, 0,'xSub') === (length - count + 1)) {
        return true;
    }
    count = 0
    count = alg(length, currentIndex, total, result, count,'yAdd');
    if (count === length || alg(length - count + 1, currentIndex, total, result, 0,'ySub') === (length - count + 1)) {
        return true;
    }
    count = 0
    count = alg(length, currentIndex, total, result, count,'xAddYSub');
    if (count === length || alg(length - count + 1, currentIndex, total, result, 0,'xSubYAdd') === (length - count + 1)) {
        return true;
    }
    count = 0
    count = alg(length, currentIndex, total, result, count,'xSubYSub');
    if (count === length || alg(length - count + 1, currentIndex, total, result, 0,'xAddYAdd') === (length - count + 1)) {
        return true;
    }
    return false;
}